<!--
  - Copyright (C) 2018-2019
  - All rights reserved, Designed By www.joolun.com
  - 注意：
  - 本软件为www.joolun.com开发研制，未经购买不得使用
  - 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
  - 一经发现盗用、分享等行为，将追究法律责任，后果自负
-->
<template>
	<view>
		<cu-custom :bgColor="'bg-'+theme.backgroundColor" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">编辑个人信息</block>
		</cu-custom>
		<form @submit="userInfoSave">

			<view class="margin radius padding-xs bg-white">
				<view class="cu-bar solid-bottom">
					<view class="action">
						<text class="cuIcon-peoplefill text-xxl text-red" :class="'text-'+theme.themeColor"></text>个人资料
					</view>
				</view>
				<view class="cu-form-group">
					<view class="title">编号</view>
					<view class="text-right text-gray">{{userInfo.userCode}}</view>
				</view>
				<view class="cu-form-group">
					<view class="title">手机号</view>
					<view class="text-right" @click="showPhoneModal">{{userInfo.phone}}<text
							class="cuIcon-right"></text></view>
				</view>
				<view class="cu-form-group">
					<view class="title">头像</view>
					<!-- #ifdef MP -->
					<!-- 微信又双叒叕换了新的头像逻辑接口 https://developers.weixin.qq.com/community/develop/doc/00022c683e8a80b29bed2142b56c01 -->
					<view class="text-right">
						<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
							<image class="avatar cu-avatar radius" :src="userInfo.headimgUrl"></image>
						</button>
					</view>
					<!-- #endif -->
					<!-- #ifndef MP -->
					<view class="text-right cu-avatar radius bg-gray"
						:style="'background-image:url('+userInfo.headimgUrl+');'" @click="chooseImage"></view>
					<!-- #endif -->
				</view>
				<view class="cu-form-group">
					<view class="title">昵称</view>
					<input class="text-right" type="nickname" placeholder="请输入昵称" name="nickName"
						:value="userInfo.nickName"></input>
				</view>
				<view class="cu-form-group">
					<view class="title">性别</view>
					<radio-group class="text-right" @change="radioChange">
						<radio class="red margin-right-xs" :class="theme.themeColor" value="1"
							:checked="userInfo.sex === '1'"></radio>男
						<radio class="red margin-left-sm margin-right-xs" :class="theme.themeColor" value="2"
							:checked="userInfo.sex === '2'"></radio>女
					</radio-group>
				</view>
				<!--  #ifdef  MP-WEIXIN -->
				<view class="cu-form-group">
					<view class="title">权限设置</view>
					<view class="text-right cuIcon-settingsfill" @tap="settings"></view>
				</view>
				<!--  #endif -->
				<view class="cu-form-group" @click="toReset">
					<view class="title">修改密码</view>
					<view class="text-right"><text class="cuIcon-right"></text></view>
				</view>
			</view>
			<view class="compile margin-top-xl">
				<button class="cu-btn shadow-blur block lg margin-sm round bottom-btn " :class="'bg-'+theme.themeColor"
					formType="submit">提交</button>
			</view>
		</form>
		<view class="cu-modal" :class="phoneModal ? ' show' : ''" style="z-index: 10!important">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">修改手机号</view>
					<view class="action" @click="hidePhoneModal">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding bg-white">
					<form @submit="phoneSub">
						<view class="cu-form-group margin-top">
							<view class="title">新号码</view>
							<input placeholder="请输入手机号" class="text-left" name="phone" v-model="form.phone"></input>
						</view>
						<view class="cu-form-group">
							<view class="title">验证码</view>
							<input placeholder="请输入验证码" class="text-left" name="code" maxlength=4 v-model="form.code"></input>
							<span @click="showGraphCodeModal" class="cu-btn bg-gray"
								:class="'display:' + msgKey">{{msgText}}</span>
						</view>
						<view class="padding flex flex-direction">
							<button class="cu-btn margin-top-sm round lg" :class="'bg-'+theme.themeColor"
								form-type="submit">提交</button>
						</view>
					</form>
				</view>
			</view>
		</view>
		<!-- 发送短信之前的图形验证码 -->
		<graph-code ref="graphCodeRef" :phone="form.phone" @onSend="getPhoneCode"></graph-code>
	</view>
</template>

<script>
	/**
	 * Copyright (C) 2018-2019
	 * All rights reserved, Designed By www.joolun.com
	 * 注意：
	 * 本软件为www.joolun.com开发研制，未经购买不得使用
	 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
	 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
	 */
	const app = getApp();
	const util = require("utils/util.js");
	import api from 'utils/api'
	import JimUtil from '@/utils/jim-util'
	import validate from 'utils/validate'
	import __config from 'config/env';
	import GraphCode from '@/components/graph-code/graph-code.vue'; // 图形验证码

	const MSGINIT = "发送验证码",
		MSGSCUCCESS = "${time}秒后可重发",
		MSGTIME = 60;
	export default {
		components:{
			GraphCode
		},
		data() {
			return {
				CustomBar: this.CustomBar,
				theme: app.globalData.theme, //全局颜色变量
				userInfo: {},
				phoneModal: false,
				form: {},
				msgText: MSGINIT,
				msgTime: MSGTIME,
				msgKey: false
			};
		},
		onLoad(options) {
			this.userInfoGet()
		},
		methods: {
			// 显示图形验证码弹框
			showGraphCodeModal() {
				if (this.msgKey) return
				if (this.form.phone == this.userInfo.phone) {
					uni.showToast({
						title: '输入号码与当前绑定号码相同',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				if (!validate.validateMobile(this.form.phone)) {
					uni.showToast({
						title: '请输入正确的手机号码',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				this.$refs.graphCodeRef.showModal()
			},
			// #ifdef MP-WEIXIN
			/**
			 * 小程序设置
			 */
			settings: function() {
				uni.openSetting({
					success: function(res) {
						console.log(res.authSetting);
					}
				});
			},
			// #endif
			//获取商城用户信息
			userInfoGet() {
				api.userInfoGet().then(res => {
					this.userInfo = res.data;
				});
			},
			radioChange(e) {
				this.userInfo.sex = e.detail.value;
			},
			uploadAvatar(filePath) { // 上传头像
        let that = this;
        api.uploadFile(filePath, 'headimg/', 'image')
            .then((link) => {
              that.userInfo.headimgUrl = link;
            })
            .catch((e) => {});
			},
			onChooseAvatar(e) {
				const {
					avatarUrl
				} = e.detail
				this.uploadAvatar(avatarUrl)
			},
			//选择头像上传
			chooseImage() {
				uni.chooseImage({
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						this.uploadAvatar(tempFilePaths[0])
					}
				});
			},
			userInfoSave(e) {
				let value = e.detail.value;
				if (!this.userInfo.headimgUrl) {
					uni.showToast({
						title: '请上传头像',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				if (!value.nickName) {
					uni.showToast({
						title: '请填写昵称',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				if (!this.userInfo.sex) {
					uni.showToast({
						title: '请选择性别',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				api.userInfoUpdate({
					id: this.userInfo.id,
					nickName: value.nickName,
					sex: this.userInfo.sex,
					headimgUrl: this.userInfo.headimgUrl
				}).then(res => {
					//更新一下im个人资料
					JimUtil.updateIMuserInfo(this.userInfo);
					uni.navigateBack({
						delta: 1
					});
				});
			},
			showPhoneModal() {
				this.phoneModal = true
			},
			hidePhoneModal() {
				this.phoneModal = false
			},
			getPhoneCode(graphCode) {
				if (this.msgKey) return
				if (this.form.phone == this.userInfo.phone) {
					uni.showToast({
						title: '输入号码与当前绑定号码相同',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				if (!validate.validateMobile(this.form.phone)) {
					uni.showToast({
						title: '请输入正确的手机号码',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				if (!graphCode) {
					uni.showToast({
						title: '请输入图形验证码',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				this.msgKey = true
				api.getPhoneCode({
					type: '2',
					phone: this.form.phone,
					graphCode
				}).then(res => {
					this.msgKey = false
					if (res.code == '0') {
						uni.showToast({
							title: '验证码发送成功',
							icon: 'none',
							duration: 3000
						});
						this.msgText = MSGSCUCCESS.replace('${time}', this.msgTime)
						this.msgKey = true
						const time = setInterval(() => {
							this.msgTime--
							this.msgText = MSGSCUCCESS.replace('${time}', this.msgTime)
							if (this.msgTime == 0) {
								this.msgTime = MSGTIME
								this.msgText = MSGINIT
								this.msgKey = false
								clearInterval(time)
							}
						}, 1000)
						this.$refs.graphCodeRef.hideModal()
					} else {
						this.$refs.graphCodeRef.refreshGraphCode()
					}
				}).catch(() => {
					this.msgKey = false
					this.$refs.graphCodeRef.refreshGraphCode()
				});
			},
			phoneSub(e) {
				if (!validate.validateMobile(this.form.phone)) {
					uni.showToast({
						title: '请输入正确的手机号码',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				if (!this.form.code) {
					uni.showToast({
						title: '请输入验证码',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				api.updateUserPhone(this.form).then(res => {
					this.userInfo.phone = this.form.phone
					this.phoneModal = false
					this.form = {}
				});
			},
			toReset() {
				uni.navigateTo({
					url: '/pages/login/register?type=editpwd'
				});
			},
		}
	};
</script>

<style>
	.avatar-wrapper {
		background-color: #ffffff;
	}

	.avatar-wrapper::after {
		border-style: none;
	}
</style>
